<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\View;

class Baidu extends BaseController
{
    /**
     * 人脸认证成功跳转地址
     */
    public function success()
    {
        $domain = $this->app->request->domain();
        $q = input('q');
        $info = Db::name('baidu_ai_verify_log')
            ->where('query_no', $q)
            ->find();
        if (!empty($info)) {
            $ai = new \baidu\Ai;
            $detail = $ai->resultDetail($info['verify_token']);
            $message = $detail['message'] ?? '';
            Db::name('baidu_ai_verify_log')
                ->where('id', $info['id'])
                ->update([
                    'result' => json_encode($detail, JSON_UNESCAPED_UNICODE),
                ]);
            View::assign('message', $message);
            
        }

        return View::fetch();
    }

    /**
     * 人脸认证失败跳转地址
     */
    public function failed()
    {
        $q = input('q');
        $info = Db::name('baidu_ai_verify_log')
            ->where('query_no', $q)
            ->find();
        if (!empty($info)) {
            $ai = new \baidu\Ai;
            $detail = $ai->resultDetail($info['verify_token']);
            $message = $detail['message'] ?? '';
            Db::name('baidu_ai_verify_log')
                ->where('id', $info['id'])
                ->update([
                    'result' => json_encode($detail, JSON_UNESCAPED_UNICODE),
                ]);
            View::assign('message', $message);

            $domain = request()->domain();
            $successUrl = urlencode($domain . '/api/baidu/success?q=' . $info['query_no']);
            $failedUrl = urlencode($domain . '/api/baidu/failed?q=' . $info['query_no']);
            $url = 'https://brain.baidu.com/face/print/?token=' . $info['verify_token'] . '&successUrl=' . $successUrl . '&failedUrl=' . $failedUrl;
            View::assign('url', $url);
        } else {
            View::assign('message', '缺少参数');
        }

        return View::fetch();
    }

    public function taste()
    {
        return View::fetch();
    } 
}